import {Component, OnInit} from '@angular/core';
import {ActivatedRoute} from '@angular/router';
import {CouponService} from '../coupon.service';
import {AliyunOssOutputUrl} from '../../../../config/api';



import {
  FormBuilder,
  FormGroup,
} from '@angular/forms';
import {Observable} from 'rxjs/Observable';

@Component({
  selector: 'app-detail',
  templateUrl: './detail.component.html',
  styleUrls: ['./detail.component.scss'],
  providers: [CouponService]
})


export class DetailComponent implements OnInit {

  cardInfo;
  aliyunOssOutputUrl =   AliyunOssOutputUrl;


  validateForm: FormGroup;
  options = [];
  groupList = [];

  termOfValidity = true;
  inStockValidity = true;
  goodsValidity = true;
  checkedGoodsTable = [];

  constructor(private fb: FormBuilder,
              private route: ActivatedRoute,
              private couponService: CouponService,
              ) {
    this.validateForm = this.fb.group({
    });
  }

  ngOnInit() {
    this.getCouponDetail();
    for (let i = 0; i < 61; i++) {
      this.options.push(i);
    }
  }

  getCouponDetail() {
    const id = +this.route.snapshot.params['id'];
    this.couponService.getCouponDetail(id).subscribe(res => {
      this.cardInfo = res.data;
      if (this.cardInfo.condition_use_in === 3) {
        this.getGroupList();
      }
      if (this.cardInfo.condition_use_in === 2) {
        this.cardInfo.card_coupons_binding_use_in.every((val, idx, array) => {
          this.getGoodsList(val.third_party_relation_id);
          return true;
        });
      }
    });
  }

  getFormControl = (name) => {
    return this.validateForm.controls[name];
  }

  // 获取店铺商品类型列表
  getGroupList() {
    this.couponService.getGroupList().subscribe(res => {
      this.groupList = res.data.data;
      if (!!this.groupList.length) {
        this.groupList.every((val, idx, array) => {
          this.cardInfo.card_coupons_binding_use_in.every((val1, idx1, array1) => {
            if (val.id === val1.third_party_relation_id) {
              val.checked = true;
              return false;
            }
            return true;
          });
          return true;
        });
      }
    });
  }

  // 获取商品列表
  getGoodsList(id: number) {
    this.couponService.getGoodsDetail(id).subscribe(res => {
      const data = {};
      data['id'] = res.data.id;
      data['name'] = res.data.name;
      data['first_picture'] = res.data.first_picture;
      data['price'] = res.data.price / 1000;
      data['in_stock'] = res.data.in_stock;
      this.checkedGoodsTable.push(data);
    });
  }
}
